<?php

namespace app\index\controller;

use app\index\model\Collect;
use app\index\model\Gallery;
use app\index\model\User;

/**
 * Class Square
 * @package app\index\controller
 */
class Square extends Base
{
    /**
     * 图库广场页面
     */
    public function index()
    {
        $galleries = model('gallery')->where('status', 1)->select();
        foreach ($galleries as $gallery) {
            $image = \app\index\model\Image::get($gallery->cover_id);
            $gallery['cover'] = $image->path;
            $user = User::get($gallery->user_id);
            $gallery['author'] = $user->nickname;
            $collect = model('collect')
                ->where(['user_id' => session('user.id'), 'gallery_id' => $gallery->id])->find();
            if ($collect) {
                $gallery['collect'] = true;
            } else {
                $gallery['collect'] = false;
            }
        }
        $this->assign('galleries', $galleries);
        return view();
    }

    /**
     * 图库详情页面
     */
    public function show($id)
    {
        $gallery = Gallery::get($id);
        if (!$gallery) {
            $this->error('图库不存在！');
        }
        if ($gallery->status != 1) {
            $this->error('无权查看此图库！');
        }
        $user = User::get($gallery->user_id);
        $gallery['author'] = $user->nickname;
        $this->assign('gallery', $gallery);
        $images = model('image')->where('gallery_id', $id)->select();
        $this->assign('images', $images);
        return view();
    }

    /**
     * 收藏或取消收藏图库
     */
    public function collect($id)
    {
        $gallery = Gallery::get($id);
        if (!$gallery) {
            $this->error('图库不存在！');
        }
        if ($gallery->status != 1) {
            $this->error('无权查看此图库！');
        }
        $collect = model('collect')
            ->where(['user_id' => session('user.id'), 'gallery_id' => $id])->find();
        if ($collect) {
            $collect->delete();
            $msg = '取消收藏成功！';
        } else {
            $collect = new Collect();
            $collect->user_id = session('user.id');
            $collect->gallery_id = $id;
            $collect->save();
            $msg = '收藏成功！';
        }
        $this->success($msg, 'index');
    }
}
